package com.joysuch.wwyt.util;

import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.joysuch.wwyt.core.common.util.MhAesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Slf4j
public class AESUtil {

    private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);

    public static final String CHARTSET = "utf-8";
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";// 默认的加密算法



    public static String encrypt(String content, String key){
        return encrypt(content,key, key);
    }


    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @param key     加密密码
     * @param iv      使用CBC模式，需要一个向量iv，可增加加密算法的强度
     * @return 加密数据
     */
    public static String encrypt(String content, String key, String iv) {
        try {
            // 创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            // 密码key(超过16字节即128bit的key，需要替换jre中的local_policy.jar和US_export_policy.jar，否则报错：Illegal
            // key size)
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARTSET), KEY_ALGORITHM);

            // 向量iv
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(CHARTSET));

            // 初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);

            // 加密
            byte[] byteContent = content.getBytes(CHARTSET);
            byte[] result = cipher.doFinal(byteContent);

            return Base64.encodeBase64String(result);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }

        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content 密文
     * @param key     密码
     * @param iv      使用CBC模式，需要一个向量iv，可增加加密算法的强度
     * @return 明文
     */
    public static String decrypt(String content, String key, String iv) {

        try {
            // 创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            // 密码key
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARTSET), KEY_ALGORITHM);

            // 向量iv
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(CHARTSET));

            // 初始化为解密模式的密码器
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);

            // 执行操作
            byte[] result = cipher.doFinal(Base64.decodeBase64(content.getBytes(CHARTSET)));

            return new String(result, CHARTSET);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }

        return null;
    }

    public static String decrypt(String content, String key) {
        return decrypt(content,key,key);
    }

    /**
     * 解密方法
     *
     * @param data 要解密的数据
     * @param key  解密key
     * @param iv   解密iv
     * @return 解密的结果
     */
    public static String desEncrypt(String data, String key, String iv){
        try {
            byte[] encrypted1 = new Base64().decode(data);
            //Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            // 性能问题： 调整为ThreadLocal
            Cipher cipher = CipherInstance.getInstance();
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original).trim();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) throws Exception {

       /* String data = "QNNmEtQ+Dfxiy1kQ7TY7iQ==";
        String key = "QAZWSXEDCRFVTGBH";
        long start = System.currentTimeMillis();
        String rt = null;
        for(int i = 0;i < 2; i++){
            long startI = System.currentTimeMillis();
            rt =  decrypt(data, key, key);
            System.out.println("..  used(s)"+ ((System.currentTimeMillis()-startI)));
        }
         // 计算总时间
       System.out.println(rt+ ".. total used(s)"+ ((System.currentTimeMillis()-start)));


        String  text = "123456";
        String keyAes = "QAZWSXEDCRFVTGBH";
        String value  = encrypt(text,keyAes);
        System.out.println(".........value ="+ value);*/
        String src = "10000000";
        String key = "QAZWSXEDCRFVTGBH";
        String encrypt = encrypt(src, key);
        System.out.println("-----加密后："+encrypt);
        String decrypt = decrypt("wexHAld0zyvrd79VjjY0oA==", key);
        System.out.println("-----解密后："+decrypt);

    }





}
